/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.wallet.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.utils.BigDecimalUtils;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.user.entity.User;
import com.pig4cloud.pigx.wallet.api.feign.RemoteRippleUserService;
import com.pig4cloud.pigx.wallet.constant.UserFundRechargeTypeEnum;
import com.pig4cloud.pigx.wallet.entity.CapitalAccount;
import com.pig4cloud.pigx.wallet.entity.RechargeRecord;
import com.pig4cloud.pigx.wallet.entity.WithdrawalRecord;
import com.pig4cloud.pigx.wallet.service.CapitalAccountService;
import com.pig4cloud.pigx.wallet.service.RechargeRecordService;
import com.pig4cloud.pigx.wallet.service.WithdrawalRecordService;
import com.pig4cloud.pigx.wallet.vo.CapitalAccountRechargeWithdrawingVO;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

import static com.pig4cloud.pigx.wallet.constant.WalletStatusEnum.RECHARGE_COMPLETED;
import static com.pig4cloud.pigx.wallet.constant.WalletStatusEnum.WITHDRAWAL_COMPLETED;

/**
 * 资金账户
 *
 * @since 2022-08-12 19:28:20
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/capitalaccount")
@Api(value = "capitalaccount", tags = "资金账户管理")
public class CapitalAccountController {

	private final CapitalAccountService capitalAccountService;

	private final RemoteRippleUserService remoteRippleUserService;

	/**
	 * 充值记录
	 */
	private final RechargeRecordService rechargeRecordService;

	/**
	 * 提现记录
	 */
	private final WithdrawalRecordService withdrawalRecordService;

	/**
	 * 分页查询
	 *
	 * @param page           分页对象
	 * @param capitalAccount 资金账户
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('wallet_capitalaccount_view')")
	public R<Page<CapitalAccount>> getCapitalAccountPage(Page<CapitalAccount> page, CapitalAccount capitalAccount) {
		List<Long> userIdList = null;
		if (StrUtil.isNotBlank(capitalAccount.getEmail())) {
			List<User> userList = remoteRippleUserService.getUserByEmail(capitalAccount.getEmail()).getData();
			if (CollUtil.isNotEmpty(userList)) {
				userIdList = userList.stream().map(User::getUid).collect(Collectors.toList());
			}
		}

		Page<CapitalAccount> list = capitalAccountService.page(page, new LambdaQueryWrapper<CapitalAccount>()
				.eq(capitalAccount.getUserId() != null, CapitalAccount::getUserId, capitalAccount.getUserId())
				.in(CollUtil.isNotEmpty(userIdList), CapitalAccount::getUserId, userIdList)
		);

		List<CapitalAccount> records = list.getRecords();
		List<Long> collect = records.stream().map(CapitalAccount::getUserId).collect(Collectors.toList());
		List<User> data = remoteRippleUserService.getUserList(collect, SecurityConstants.FROM_IN).getData();

		records.forEach(record -> {
			data.forEach(item -> {
				if (record.getUserId().equals(item.getUid())) {
					record.setEmail(item.getEmail());
				}
			});

			// 向下取值
			record.setAvailable(record.getAvailable().setScale(2, RoundingMode.DOWN));
			record.setFrozen(record.getFrozen().setScale(2, RoundingMode.DOWN));
			record.setTotalAssets(record.getAvailable().add(record.getFrozen()).setScale(2, RoundingMode.DOWN));
		});

		return R.ok(list);
	}

	/**
	 * 通过id查询资金账户
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('wallet_capitalaccount_view')")
	public R<CapitalAccount> getById(@PathVariable("id") Long id) {
		return R.ok(capitalAccountService.getById(id));
	}

	/**
	 * 新增资金账户
	 *
	 * @param capitalAccount 资金账户
	 * @return R
	 */
	@ApiOperation(value = "新增资金账户", notes = "新增资金账户")
	@SysLog("新增资金账户")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('wallet_capitalaccount_add')")
	public R<Boolean> save(@RequestBody CapitalAccount capitalAccount) {
		return R.ok(capitalAccountService.save(capitalAccount));
	}

	/**
	 * 修改资金账户
	 *
	 * @param capitalAccount 资金账户
	 * @return R
	 */
	@ApiOperation(value = "修改资金账户", notes = "修改资金账户")
	@SysLog("修改资金账户")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('wallet_capitalaccount_edit')")
	@GlobalTransactional(rollbackFor = Throwable.class)
	public R<Boolean> updateById(@RequestBody CapitalAccount capitalAccount, HttpServletRequest request) {
		Enumeration<String> headerNames = request.getHeaderNames();
		capitalAccountService.updateCapitalAccountById(capitalAccount);
		return R.ok();
	}

	/**
	 * 通过id删除资金账户
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除资金账户", notes = "通过id删除资金账户")
	@SysLog("通过id删除资金账户")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('wallet_capitalaccount_del')")
	public R<Boolean> removeById(@PathVariable Long id) {
		return R.ok(capitalAccountService.removeById(id));
	}


	/**
	 * 导出excel 表格
	 *
	 * @param capitalAccount 查询条件
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	@PreAuthorize("@pms.hasPermission('wallet_capitalaccount_export')")
	public List<CapitalAccount> export(CapitalAccount capitalAccount) {
		return capitalAccountService.list(Wrappers.query(capitalAccount));
	}

	/**
	 * web根据用户id获取充提总额统计
	 *
	 * @param id 用户id
	 * @return 充提总额信息
	 */
	@ApiOperation(value = "web根据用户id获取充提总额统计", notes = "web根据用户id获取充提总额统计")
	@GetMapping("/page/accountRechargeInfo")
	public R<CapitalAccountRechargeWithdrawingVO> getRechargeWithdrawalInformationByUserId(Long id) {
		CapitalAccountRechargeWithdrawingVO capitalAccountInfoVO = new CapitalAccountRechargeWithdrawingVO();
		// 充值总金额
		RechargeRecord totalAmountRecharge = rechargeRecordService.getOne(new QueryWrapper<RechargeRecord>()
				.select("SUM(quantity) AS quantity")
				.eq("user_id", id)
				// 充值状态 已完成
				.eq("state", RECHARGE_COMPLETED.getStatus())
				.eq("del_flag", "0"));
		if (totalAmountRecharge != null) {
			capitalAccountInfoVO.setTotalAmountRecharge(BigDecimalUtils.toStrRemoveExtraZero(totalAmountRecharge.getQuantity()));
		} else {
			capitalAccountInfoVO.setTotalAmountRecharge(String.valueOf(BigDecimal.ZERO));
		}
		// 区块链充值总金额
		RechargeRecord blockchainRecharge = rechargeRecordService.getOne(new QueryWrapper<RechargeRecord>()
				.select("SUM(quantity) AS quantity")
				.eq("user_id", id)
				.eq("type", UserFundRechargeTypeEnum.RECHARGE.getCode())
				// 充值状态 已完成
				.eq("state", RECHARGE_COMPLETED.getStatus())
				.eq("del_flag", "0"));
		if (blockchainRecharge != null) {
			capitalAccountInfoVO.setBlockchainRecharge(BigDecimalUtils.toStrRemoveExtraZero(blockchainRecharge.getQuantity()));
		} else {
			capitalAccountInfoVO.setBlockchainRecharge(String.valueOf(BigDecimal.ZERO));
		}
		// 区块链提现总金额
		WithdrawalRecord blockchainWithdrawal = withdrawalRecordService.getOne(new QueryWrapper<WithdrawalRecord>()
				.select("SUM(quantity) AS quantity")
				.eq("user_id", id)
				// 提现状态 已完成
				.eq("state", WITHDRAWAL_COMPLETED.getStatus())
				.eq("del_flag", "0"));
		if (blockchainWithdrawal != null) {
			capitalAccountInfoVO.setBlockchainWithdrawal(BigDecimalUtils.toStrRemoveExtraZero(blockchainWithdrawal.getQuantity()));
		} else {
			capitalAccountInfoVO.setBlockchainWithdrawal(String.valueOf(BigDecimal.ZERO));
		}
		// 返佣累计
		RechargeRecord commissionCumulative = rechargeRecordService.getOne(new QueryWrapper<RechargeRecord>()
				.select("SUM(quantity) AS quantity")
				.eq("user_id", id)
				// 充值状态 已完成
				.eq("state", RECHARGE_COMPLETED.getStatus())
				.eq("type", UserFundRechargeTypeEnum.REBATE)
				.eq("del_flag", "0"));
		if (commissionCumulative != null) {
			capitalAccountInfoVO.setCommissionCumulative(BigDecimalUtils.toStrRemoveExtraZero(commissionCumulative.getQuantity()));
		} else {
			capitalAccountInfoVO.setCommissionCumulative(String.valueOf(BigDecimal.ZERO));
		}
		return R.ok(capitalAccountInfoVO);
	}

}
